package com.orange.notificationsummary.utils;

import java.io.IOException;
import java.io.InputStream;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.text.TextUtils;

public class MessageUtils {
	private static final String	TAG					= "MessageUtils";
	private static final Uri	MMS_SMS_ADDRESS_URI	= Uri.parse("content://mms-sms/canonical-addresses");
	private static final String	ADDRESS				= "address";
	private static final String	_ID					= "_id";

	public static Bitmap getContactPhoto(String number, boolean isSMS,
			ContentResolver cv) {
		Bitmap bitmap = null;
		Long id = null;

		if (isSMS) {
			number = getSmsNumber(number, cv);
		}

		// if (number != null && !number.equals("")) {
		if (!TextUtils.isEmpty(number)) {
			Cursor cursor = null;
			try {
				cursor = cv.query(Uri.withAppendedPath(
						PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)),
						new String[] { PhoneLookup._ID }, null, null, null);

				if (cursor != null && cursor.moveToFirst()) {
					id = cursor.getLong(0);
				}
			} catch (Exception e) {
				LogHelper.e(TAG, "getContactPhoto. ", e);
			} finally {
				if (cursor != null) {
					cursor.close();
				}
			}

			if (id == null) {
				return null;
			}

			bitmap = getContactPhotoBitmap(cv, id);
		}

		return bitmap;

	}

	private static Bitmap getContactPhotoBitmap(ContentResolver cv,
			Long contactId) {
		Bitmap bitmap = null;

		Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
				contactId);

		InputStream inputStream = ContactsContract.Contacts
				.openContactPhotoInputStream(cv, contactUri);
		if (inputStream != null) {
			bitmap = BitmapFactory.decodeStream(inputStream);
			try {
				inputStream.close();
			} catch (IOException e) {
				LogHelper.e(TAG, "getContactPhotoBitmap. ", e);
			}
		}

		return bitmap;
	}

	private static String getSmsNumber(String id, ContentResolver cv) {
		String smsNumber = "";
		if (id != null && !id.equals("")) {
			Cursor cursor = null;
			try {
				cursor = cv.query(MMS_SMS_ADDRESS_URI,
						new String[] { ADDRESS }, _ID + " = ?",
						new String[] { id }, null);

				while (cursor.moveToNext()) {
					for (int i = 0; i < cursor.getColumnCount(); i++) {
						smsNumber = cursor.getString(cursor
								.getColumnIndex(ADDRESS));
					}
				}
			} catch (Exception e) {
				LogHelper.e(TAG, "getSmsNumber. ", e);
			} finally {
				if (cursor != null)
					cursor.close();
			}
		}
		return smsNumber;
	}
}
